<?php

namespace App\Kuafu\Statistics\Controller\B;

use App\Kuafu\Export\Enum\ExportCodeEnum;
use App\Kuafu\Export\Model\ExportDownloadModel;
use App\Kuafu\Export\Service\ExportDownloadService;
use App\Kuafu\Export\Service\ExportFactory\ExportWebInOrderService;
use App\Kuafu\Order\Enum\CodeEnum;
use App\Kuafu\Order\Enum\OrderCodeEnum;
use App\Kuafu\Order\Enum\OrderMerchantEnum;
use App\Kuafu\Order\Service\OrderStatisticsService;
use App\Kuafu\Statistics\Service\StatisticsService;
use App\Support\Util;
use Illuminate\Http\Request;
use App\Kuafu\Base\Controller\BaseController;
use PHP_CodeSniffer\Reports\Code;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

class StatisticsController extends BaseController
{
    protected function paymentParams(Request $request): array
    {

        $shopId               = (int)$request->get('shopId', 0);
        $payChannel           = (int)$request->get('payChannel', 0);
        $startDate            = (string)$request->get('startDate', '');
        $endDate              = (string)$request->get('endDate', '');
        $payChannelMerchantId = (string)$request->get('payChannelMerchantId', '');
        $pageSize             = (int)$request->get('pageSize', 20);
        $pageNum              = (int)$request->get('pageNum', 1);
        return compact('shopId', 'payChannel', 'startDate', 'endDate', 'payChannelMerchantId', 'pageSize', 'pageNum');
    }

    public function paymentIndex(Request $request)
    {
        $this->validate($request, [
            'startDate' => 'required|date',
            'endDate'   => 'required|date',
            'shopIds'    => 'required|integer',
        ], [
            'startDate.required' => "开始日期不能为空",
            'endDate.required'   => "结束日期不能为空",
            'shopIds.required'    => "门店不能为空",
        ]);

        extract($this->paymentParams($request));
        $shopId = (int)$request->get('shopIds');
        $data   = StatisticsService::paymentList($shopId, $payChannel, $startDate, $endDate, $payChannelMerchantId,
            $pageNum, $pageSize);
        return $this->success($data);
    }

    public function paymentExcel(Request $request)
    {
        $this->validate($request, [
            'startDate' => 'required|date',
            'endDate'   => 'required|date',
            'shopIds'    => 'required|integer',
        ], [
            'startDate.required' => "开始日期不能为空",
            'endDate.required'   => "结束日期不能为空",
            'shopIds.required'    => "门店不能为空",
        ]);

        extract($this->paymentParams($request));
        $shopId = (int)$request->get('shopIds');
        if (empty($startDate) || empty($endDate)) {
            return $this->fail(OrderCodeEnum::ERR_400000, '请选择导出日期');
        }
        $tmpFilePath = StatisticsService::paymentExcel($shopId, $payChannel, $startDate, $endDate,
            $payChannelMerchantId);
        return (new BinaryFileResponse($tmpFilePath, 200, [
            'Content-Disposition' => 'attachment;filename=' . urlencode(basename($tmpFilePath)),
            'Content-Type'        => 'application/octet-stream',
        ]))->deleteFileAfterSend();
    }

    //综合营业统计
    public function comprehensiveList(Request $request)
    {
        // 判断当前时间是否满足空闲时间
//        $now = date('H');
//        if (($now > 11 && $now < 14) || ($now > 15 && $now < 20)) {
//            return $this->fail(0, '11:00~14:00，15:00~20:00 期间禁止查询、导出。');
//        }

        $monthDate = $request->monthDate;
        $today     = $request->get('today', 0);
        extract($this->paymentParams($request));
        $data = StatisticsService::comprehensiveList($shopId, $monthDate, $today);
        return $this->success($data);
    }

    public function comprehensiveExcel(Request $request)
    {
//        // 判断当前时间是否满足空闲时间
//        $now = date('H');
//        if (($now > 11 && $now < 14) || ($now > 15 && $now < 20)) {
//            return $this->fail(0, '11:00~14:00，15:00~20:00 期间禁止查询、导出。');
//        }

        $monthDate = $request->monthDate;
        $today     = $request->get('today', 0);
        extract($this->paymentParams($request));
        $tmpFilePath = StatisticsService::comprehensiveStatistics($shopId, $monthDate, $today);
        return (new BinaryFileResponse($tmpFilePath, 200, [
            'Content-Disposition' => 'attachment;filename=' . urlencode(basename($tmpFilePath)),
            'Content-Type'        => 'application/octet-stream',
        ]))->deleteFileAfterSend();
    }

    public function shopOrderExcel(Request $request)
    {
        $shopId            = $request->shopId;
        $payChannel        = $request->payChannel;
        $sourceType        = $request->sourceType;
        $completeTimeStart = $request->completeTimeStart;
        $completeTimeEnd   = $request->completeTimeEnd;
        if (empty($completeTimeStart) || empty($completeTimeEnd)) {
            return $this->fail(OrderCodeEnum::ERR_400000, '请选择导出日期');
        }
        if (Util::isDate($completeTimeStart)) {
            $completeTimeStart .= ' 00:00:00';
        }
        if (Util::isDate($completeTimeEnd)) {
            $completeTimeEnd .= ' 23:59:59';
        }

        if (is_int($shopId)) {
            $shopIds = [$shopId];
        } else {
            $shopIds = explode(',', $shopId);
        }

        // 订单条数
        $row = 0;

        if (count($shopIds) > 1) {
            $row = 99999;
        } else {
            foreach ($shopIds as $shopId) {
                $row += OrderStatisticsService::getOrderMappingData($shopId, $payChannel, $sourceType,
                    $completeTimeStart, $completeTimeEnd, false);
            }
        }

        if (isTest()) {
            $rowDiff = 50;
        } else {
            $rowDiff = 1000;
        }

        if ($row >= $rowDiff) {

            // 异步队列导出
            $client            = ExportDownloadModel::CLIENT_TYPE_WEB;
            $fileType          = ExportDownloadModel::FILE_TYPE_WEB_IN_ORDER;
            $completeTimeStart = strtotime($completeTimeStart);
            $completeTimeEnd   = strtotime($completeTimeEnd);
            ExportDownloadService::export($client, $fileType, 0, OrderMerchantEnum::SHOW_TIME_TAB_DEFINE,
                $completeTimeStart, $completeTimeEnd, $shopIds);

            return $this->json([
                'code' => ExportCodeEnum::ERR_EXPORT_ING,
                'msg'  => '导出中',
                'data' => ['num' => $row]
            ]);
        }

        // 正常数据流导出
        ExportWebInOrderService::streamExport($shopIds, $completeTimeStart, $completeTimeEnd, '');
    }
}
